<!--
  Radio 单选框组件                 zls-2022/06/04
    所有属性、事件、方法、插槽，请参考  https://vant-contrib.gitee.io/vant/#/zh-CN/radio
  
    Attributes
      1、list       多选框列表数据，格式为 [{ text: '复选框1', code: '1' }]
-->
<template>
  <Field
    class="z-input"
    :name="$attrs['name']"
    :label="$attrs['label']"
    :required="$attrs['required']"
    :rules="$attrs['required'] || $attrs['required'] === '' ? [{ required: true, message: '请选择' }] : []"
    :placeholder="$attrs['placeholder'] || '请选择'"
    :border="$attrs['border']"
    :colon="$attrs['colon']"
    :label-width="$attrs['label-width']"
    @click="show = true"
  >
    <template #input>
      <RadioGroup v-model="checked" :disabled="$attrs['disabled']" :direction="$attrs['direction'] || 'horizontal'" :icon-size="$attrs['icon-size']" @change="change">
        <Radio
          v-for="(item, i) in props.list"
          :key="i"
          :name="item.code"
          :shape="$attrs['shape']"
          :disabled="item.disabled"
          :label-disabled="$attrs['label-disabled']"
          :label-position="$attrs['label-position']"
          >{{ item.text }}
        </Radio>
      </RadioGroup>
    </template>
    <template #right-icon>
      <z-svg name="chahao" v-if="checked" @click.stop="clear"></z-svg>
    </template>
  </Field>
</template>

<script>
export default { name: 'z-radio' }
</script>
<script setup>
import { watch, ref, useAttrs } from 'vue'
import { Field, RadioGroup, Radio } from 'vant'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  }
})
const attrs = useAttrs()

const checked = ref('') // 是否选中

watch(
  () => attrs.modelValue,
  newVal => {
    checked.value = newVal ?? ''
  },
  { immediate: true, deep: true }
)

function clear() {
  emit('update:modelValue', '')
}

function change(val) {
  emit('update:modelValue', val)
}
</script>

<style lang="scss" scoped>
.van-radio {
  margin-bottom: 6px;
}
</style>
